/**
 * 
 */
package leetCode;

/**
 * @author zhong
 *
 */
public class PushDominoes {
	public String pushDominoes(String dominoes) {
		int n = dominoes.length();

		StringBuilder reStringBuilder = new StringBuilder();
		int i = 0;
		while (i < n) {
			int dotCnt = 0;// 记录连续的.
			while (i < n && dominoes.charAt(i) == '.') {
				dotCnt++;
				i++;
			}
			if (i == n) {
				for (int j = 0; j < dotCnt; j++) {
					reStringBuilder.append('.');
				}
				break;
			}

			if (dominoes.charAt(i) == 'R') {// 如果是R，则向后找.和后一个字符
				for (int j = 0; j < dotCnt; j++) {// 之前的.不被推到
					reStringBuilder.append('.');
				}
				reStringBuilder.append('R');
				if (i < n - 1 && dominoes.charAt(i + 1) == '.') {// 后面有.要处理
					// 记录.个数
					i++;
					dotCnt = 0;
					while (i < n && dominoes.charAt(i) == '.') {
						dotCnt++;
						i++;
					}

					if (i < n && dominoes.charAt(i) == 'L') {// 后一个字符是L，则向中间处理
						int cnt = dotCnt / 2;
						for (int j = 0; j < cnt; j++) {
							reStringBuilder.append('R');
						}
						if (dotCnt % 2 == 1) {
							reStringBuilder.append('.');
						}
						for (int j = 0; j <= cnt; j++) {
							reStringBuilder.append('L');
						}
						i++;
					} else {// 下一个是R，则不影响当前R，结果增加dotCnt个R
						for (int j = 0; j < dotCnt; j++) {
							reStringBuilder.append('R');
						}
					}
				} else {
					i++;
				}
			} else {// 当前是L，则把前面.变为L，并加上当前L
				for (int j = 0; j <= dotCnt; j++) {
					reStringBuilder.append('L');
				}
				i++;
			}
		}
		return reStringBuilder.toString();
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String string = ".L.R...LR..L..";// "RR.L";
		System.out.println(new PushDominoes().pushDominoes(string));
	}

}
